var app = getApp()
var server = app.globalData.server;
var util = require('../../utils/util')
Page({

  /**
   * 页面的初始数据
   */
  data: {
    genderList: [{
        "sex": "男",
        "flag": true
      },
      {
        "sex": "女",
        "flag": false
      }
    ],
    btn: '修改信息',
    z: -1,
    join: false,
    name: '',
    phone: '',
    address_label: '',
    sex: '男',
    shop: '',
    img: [],
    number: '',
    address: '',
    address_name: '',
    detail: '',
    whetherEmpower: 'yes',
  },
  select(e) {
    let genderList = this.data.genderList;
    let index = e.currentTarget.dataset.index;
    console.log(index);
    for (let i in genderList) genderList[i].flag = false
    genderList[index].flag = true;
    this.setData({
      genderList,
      sex: genderList[index].sex
    })
  },
  inputName(e) {
    this.setData({
      name: e.detail.value
    })
  },
  inputPhone(e) {
    this.setData({
      phone: e.detail.value
    })
  },
  inputShop(e) {
    this.setData({
      shop: e.detail.value
    })
  },
  inputNumber(e) {
    this.setData({
      number: e.detail.value
    })
  },
  inputAddress(e) {
    this.setData({
      address: e.detail.value
    })
  },
  inputAddress_name(e) {
    this.setData({
      address_name: e.detail.value
    })
  },
  inputDetail(e) {
    this.setData({
      detail: e.detail.value
    })
  },
  async chooseLocation(e) {
    var that = this;
    var auth;
    await new Promise((resolve,reject)=>{
      wx.showLoading({
        title: '调取中',
      })
      wx.getSetting({success:function(res){
        wx.hideLoading()
        auth=res.authSetting
        resolve(res.authSetting)
      }})
    })
    if(auth['scope.userLocation']){
      wx.chooseLocation({
        success: function (res) {
          console.log(res)
          let addressJson = res;
          wx.setStorageSync('addressJson', addressJson)
          that.setData({
            address: res.address,
            address_name: res.name,
            modalName: 'address',
            z: 200
          })
        },
        fail:function(res){
          console.log(res)
        }
      })
    }else{
      wx.showModal({
        title:'未允许获取位置信息，请确认是否已开启【位置信息】，允许获取位置信息。',
        success:function(res){
          console.log(res)
          if(res.confirm){
            wx.openSetting({
              withSubscriptions: true,
            })
          }
        }
      })
    }
  },
  changeInput: function () {
    var _this = this;
    this.hideModal()
    setTimeout(res => {
      _this.setData({
        whetherEmpower: 'no'
      })
    })
  },
  hideModal(e) {
    if (this.data.modalName == 'address') {
      let string = this.data.address + this.data.detail;
      let label = ''
      label = '...' + string.substring(string.length - 7, string.length)
      this.setData({
        address_label: label
      })
    }
    this.setData({
      modalName: null,
      z: -1,
    })
  },

  ChooseImage() {
    wx.chooseImage({
      count: 1, //默认9
      sizeType: ['original', 'compressed'], //可以指定是原图还是压缩图，默认二者都有
      sourceType: ['album', 'camera'], //从相册选择
      success: (res) => {
        this.setData({
          img: res.tempFilePaths
        })
      }
    });
  },

  ViewImage(e) {
    var img=this.data.img;
    for(let i in img){
      img[i]=util.link(img[i])
      this.setData({img:img})
    }
    wx.previewImage({
      urls: img,
      current: img[e.target.dataset.index]
    });
  },

  DelImg(e) {
    let img = this.data.img;
    wx.showModal({
      content: '确定要删除图片吗？',
      cancelText: '取消',
      confirmText: '确定',
      success: res => {
        if (res.confirm) {
          img.splice(0, 1);
          this.setData({
            img
          })
        }
      }
    })
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    wx.hideHomeButton();
    if (!wx.getStorageSync('userInfo')) {
      let profile;
      if (wx.getUserProfile) {
        profile=1;
      }else{
        profile=0;
      }
      this.selectComponent("#authorize").showModal("#0178C1",profile);
    }
    if (options.type) {
      console.log(options.type)
      this.setData({
        btn: '注册',
        join: true
      })
      console.log(this.data.type)
    } else {
      var that = this;
      let data = JSON.parse(options.data)
      let string = data.address + data.detail;
      let img=[]
      img.push(data.payment_img)
      that.setData({
        name: data.name,
        phone: data.phone,
        sex: data.sex,
        shop: data.shop,
        img: img,
        number: data.number,
        address_label: '...' + string.substring(string.length - 7, string.length),
        address: data.address,
        detail: data.detail,
        address_name: data.address_name
      })
    }
    let isIphoneX = app.globalData.isIphoneX;
    console.log(isIphoneX)
    this.setData({
      isIphoneX
    })

    wx.hideHomeButton({
      success: () => {
        console.log(1111)
      }
    })
  },

  submit: function (e) {
    var that = this;
    if (that.data.phone != '') {
      var reg = /^1[3|4|5|6|7|8|9][0-9]{9}$/; //验证规则
      var flag = reg.test(that.data.phone); //true
      console.log(flag)
      if (flag === false) {
        wx.showToast({
          title: '手机号错误',
          icon: 'none',
          duration: 1000
        })
        return
      }
    }
    if (that.data.name == '' || that.data.phone == '' || that.data.address == '' || that.data.shop == '' || that.data.img == '') {
      wx.showToast({
        title: '请填写完整内容',
        icon: 'none',
        duration: 1000
      })
      return
    }
    if (!wx.getStorageSync('userInfo')) {
      let profile;
      if (wx.getUserProfile) {
        profile=1;
      }else{
        profile=0;
      }
      this.selectComponent("#authorize").showModal("#0178C1",profile);
    } else {
      console.log(that.data.detail)
      getApp().preventActive(async (res) => {
        if (!app.globalData.PageActive) {
          switch (that.data.btn) {
            case '修改信息':
              wx.showModal({
                title:'保存修改的信息',
                success:function(res){
                  if(res.confirm){
                    wx.showLoading({
                      title: '提交中',
                    })
                    util.request('/sales/update', {
                      phone: that.data.phone,
                      number: that.data.number,
                      detail: that.data.detail,
                      openid: app.globalData.openid
                    }, 'POST').then(res => {
                      wx.hideLoading()
                      wx.showToast({
                        title: '修改成功',
                        icon: 'success',
                        duration: 2000
                      })
                      setTimeout(() => {
                        wx.navigateBack({
                          delta: 0,
                        })
                      }, 2000)
                    })
                  }
                }
              })
              break;
            default:
              wx.showLoading({
                title: '注册中',
              })
              wx.uploadFile({
                url: server + '/upload/image', //仅为示例，非真实的接口地址
                filePath: that.data.img[0],
                name: 'file',
                formData: {
                  'catalog': 'payment'
                },
                success(res) {
                  console.log(res)
                  let img = res.data;
                  let addressJson = wx.getStorageSync('addressJson')
                  util.request('/sales/insert', {
                    name: that.data.name,
                    openid: app.globalData.openid,
                    sex: that.data.sex,
                    phone: that.data.phone,
                    shop: that.data.shop,
                    address: that.data.address,
                    address_name: that.data.address_name,
                    detail: that.data.detail,
                    lon: addressJson.longitude,
                    lat: addressJson.latitude,
                    number: that.data.number,
                    payment_img: img,
                    creation_timestamp: Date.parse(util.formatTime(new Date()).replace(/-/g, '/')) / 1000,
                  }, 'POST').then(res => {
                    wx.hideLoading()
                    wx.showToast({
                      title: '注册成功',
                      icon: 'success',
                      duration: 2000
                    })
                    setTimeout(() => {
                      wx.redirectTo({
                        url: '../salesperson/salesperson',
                      })
                    }, 2000)
                  })
                },
                fail: function (res) {
                  console.log(res)
                }
              })

          }
        }
      })
    }

  },
  lookupAddress: function () {
    this.setData({
      modalName: 'address',
      z: 200
    })
    console.log(this.data.modalName,this.data.z)
  },
  phoneModal: function () {
    this.setData({
      modalName: 'phoneModal',
      z: 200
    })
  },
  getPhoneNumber: function (e) {
    var that = this;
    //console.log(e)
    if (e.detail.errMsg == "getPhoneNumber:ok") {
      wx.showLoading({
        title: '授权中',
      })
      wx.cloud.callFunction({
        name: 'decode',
        data: {
          weRunData: wx.cloud.CloudID(e.detail.cloudID),
        }
      }).then(res => {
        that.setData({
          phone: res.result,
        })
        wx.hideLoading()
        that.hideModal();
        wx.showToast({
          title: '授权成功',
          icon: 'success'
        })
      }).catch(error => {
        console.log(error);
        wx.hideLoading()
        wx.showToast({
          title: '授权失败',
          icon: 'none'
        })
      })

    }
  },
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    wx.getLocation({
      success(res) {
        console.log(res)
      }
    })
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  // onShareAppMessage: function () {

  // }
})